<template>
  <div class="mo-input-number">
    <template v-if="multiple === 'radio'">
      <el-input
        @input="limitInput($event)"
        v-model.trim="form"
        v-bind="attribute"
      ></el-input>
    </template>
    <template v-else>
      <span
        v-for="(item, index) in count"
        :key="item"
        class="input-number-item"
      >
        <el-input
          @input="limitInput($event, item)"
          v-model.trim="form[item]"
          v-bind="attribute"
        ></el-input
        ><span></span>
        <span v-if="index + 1 !== count.length" class="drop">*</span>
      </span>
    </template>
  </div>
</template>

<script>
export default {
  name: "CheckeInputNumber",
  props: {
    value: {
      type: [Object, String],
      require: true,
    },
    multiple: {
      type: String,
      validator(value) {
        return ["radio", "checked"].includes(value);
      },
      default: "radio",
    },

    attribute: {
      type: Object,

      default: () => ({}),
    },
  },
  watch: {
    form: {
      handler(val) {
        this.$emit("change", val);
      },
      deep: true,
    },
  },
  data() {
    return {
      count: ["mik1", "mik2", "mik3"],
      form: this.value,
    };
  },

  mounted() {},

  methods: {
    limitInput(value, name = "") {
      let val =
        ("" + value) // 第一步：转成字符串
          .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数

      if (name) {
        this.form[name] = val;
      } else {
        this.form = val;
      }
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
};
</script>

<style lang="less" scoped>
.mo-input-number {
  display: flex;
}
.input-number-item {
  display: flex;
  align-items: center;
}
.drop {
  padding: 0 8px;
}
</style>
